import SwiftUI
import PhotosUI

struct RealName_Picker: UIViewControllerRepresentable {
    @Environment(\.dismiss) var dismiss
    
    @Binding var imageURL: URL?
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<RealName_Picker>) -> PHPickerViewController {
        var configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
        configuration.filter = .images
        configuration.preferredAssetRepresentationMode = .current

        let photoPickerViewController = PHPickerViewController(configuration: configuration)
        photoPickerViewController.delegate = context.coordinator
        return photoPickerViewController
    }
    
    func makeCoordinator() -> RealName_Coordinator {
        RealName_Coordinator(self)
    }

    func updateUIViewController(_ uiViewController: PHPickerViewController, context: UIViewControllerRepresentableContext<RealName_Picker>) {
    }
}

class RealName_Coordinator: NSObject, UINavigationControllerDelegate, PHPickerViewControllerDelegate {
    let parent: RealName_Picker
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        guard
            let result = results.first,
            result.itemProvider.hasItemConformingToTypeIdentifier(UTType.image.identifier)
        else { return }
        
        result.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier) { url, error in
            if let error = error {
                print("Error loading file representation: \(error.localizedDescription)")
            } else if let url = url {
                if let savedUrl = FileManager.default.copyItemToDocumentDirectory(from: url) {
                    self.parent.imageURL = savedUrl
                    self.parent.dismiss()
                }
            }
        }
    }
    
    init(_ parent: RealName_Picker) {
        self.parent = parent
    }
}
